// 管理页面JavaScript
// 等待所有脚本加载完成
window.addEventListener('load', function () {
    console.log('------------------------ 管理页面加载调试信息 ------------------------');
    // 获取所有标签按钮和标签内容
    const tabButtons = document.querySelectorAll('.tab-button');
    const tabContents = document.querySelectorAll('.tab-content');


    // 确保所有标签内容都有hidden类，除了当前激活的
    tabContents.forEach(content => {
        if (!content.classList.contains('hidden')) {
            content.classList.add('hidden');
        }
    });
    // 初始化顶部通知卡片
    initTopNotification();


// 初始化页面
    handleUrlParams();

// 初始化包裹管理相关事件
    initPackageEventListeners();

    // 标签按钮点击事件
    tabButtons.forEach(button => {
        button.addEventListener('click', function () {
            const tabId = this.getAttribute('data-tab');
            activateTab(tabId);
        });
    });


    // 更新页面标题和描述
    function updatePageTitleAndDescription(tabId) {
        const pageTitle = document.getElementById('page-title');
        const pageDescription = document.getElementById('page-description');

        const titles = {
            'users': '用户管理',
            'couriers': '物流员管理',
            'packages': '包裹查询',
            'roles': '角色权限管理',
            'routes': '路线管理',
            'exceptions': '异常处理'
        };

        const descriptions = {
            'users': '管理系统用户账号和权限',
            'couriers': '管理物流员信息和配送任务',
            'packages': '查询和管理包裹配送状态',
            'roles': '管理用户角色和权限分配',
            'routes': '管理配送路线和区域划分',
            'exceptions': '处理配送过程中的异常情况'
        };

        if (pageTitle && titles[tabId]) {
            pageTitle.textContent = titles[tabId];
        }

        if (pageDescription && descriptions[tabId]) {
            pageDescription.textContent = descriptions[tabId];
        }
    }


// 激活指定标签页
    function activateTab(tabId) {
        console.log('激活标签页:', tabId);

        // 移除所有标签按钮的active类
        tabButtons.forEach(button => {
            button.classList.remove('active');
        });

        // 隐藏所有标签内容
        tabContents.forEach(content => {
            content.classList.add('hidden');
        });

        // 添加当前标签按钮的active类
        const activeButton = document.querySelector(`.tab-button[data-tab='${tabId}']`);
        if (activeButton) {
            activeButton.classList.add('active');
        }

        // 显示当前标签内容
        const activeContent = document.getElementById(`${tabId}-tab`);
        if (activeContent) {
            activeContent.classList.remove('hidden');
        }

        // 更新页面标题和描述
        updatePageTitleAndDescription(tabId);
    }




// 处理URL参数
function handleUrlParams() {
    const urlParams = new URLSearchParams(window.location.search);
    const tabType = urlParams.get('type');

    if (tabType) {
        // 激活对应标签页
        activateTab(tabType);
    }
}

// 初始化角色表格
function initRoleTable() {
    console.log('初始化角色表格数据...');
    // 这里可以添加初始化角色表格的逻辑
    // 例如模拟API请求获取角色数据并填充表格
    
    // 检查角色表格是否存在
    const rolesTab = document.getElementById('roles-tab');
    if (rolesTab && !rolesTab.classList.contains('hidden')) {
        // 模拟加载数据的延迟
        setTimeout(() => {
            console.log('角色表格数据加载完成');
            // 这里可以添加实际的数据加载逻辑
        }, 500);
    }
}


// 打开查看包裹模态框
function openViewPackageModal(trackingNumber, sender, senderPhone, receiver, receiverPhone, address) {
    const viewPackageModal = document.getElementById('view-packages-modal');
    if (viewPackageModal) {
        // 填充包裹数据
        document.getElementById('view-package-tracking-number').textContent = trackingNumber;
        document.getElementById('view-package-sender').textContent = sender;
        document.getElementById('view-package-sender-phone').textContent = senderPhone;
        document.getElementById('view-package-receiver').textContent = receiver;
        document.getElementById('view-package-receiver-phone').textContent = receiverPhone;
        document.getElementById('view-package-address').textContent = address;

        // 移除hidden类以显示模态框
        viewPackageModal.classList.remove('hidden');
        updateModalOverlay();
    }
}

// 关闭查看包裹模态框
function closeViewPackageModal() {
    const viewPackageModal = document.getElementById('view-packages-modal');
    if (viewPackageModal) {
        viewPackageModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 初始化包裹详情模态框事件
function initPackageModalEvents() {
    const viewPackageModal = document.getElementById('view-packages-modal');
    const closeViewModalBtn = document.querySelector('#view-packages-modal .close-modal');

    // 关闭按钮事件
    if (closeViewModalBtn) {
        closeViewModalBtn.addEventListener('click', closeViewPackageModal);
    }

    // 点击模态框外部关闭
    window.addEventListener('click', function (event) {
        if (event.target === viewPackageModal) {
            closeViewPackageModal();
        }
    });
}

// 在页面加载时初始化包裹模态框事件
window.addEventListener('load', initPackageModalEvents);

// 在DOM加载完成后初始化路线事件监听器和模态框遮罩
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，初始化路线事件监听器和模态框遮罩');
    initRouteEventListeners();
    initModalOverlay();
});


});

// 初始化模态框背景遮罩
var modalOverlay;

function initModalOverlay() {
    modalOverlay = document.querySelector('.modal-overlay');
    if (modalOverlay) {
        // 当点击背景遮罩时关闭所有模态框
        modalOverlay.addEventListener('click', function () {
            document.querySelectorAll('.modal').forEach(modal => {
                modal.classList.add('hidden');
            });
            modalOverlay.classList.add('hidden');
        });
    }
}

// 在页面加载时初始化
window.addEventListener('load', function() {
    initModalOverlay();
    initModalCloseButtons();
    initRoleEventListeners();
});

// 初始化顶部通知卡片和模态框
function initTopNotification() {
    // 初始化添加物流员按钮事件
    const addCourierBtn = document.getElementById('add-courier-btn');
    if (addCourierBtn) {
        addCourierBtn.addEventListener('click', function () {
            openAddCourierModal();
        });
    }

    // 初始化添加物流员模态框相关元素和事件
    const addCourierModal = document.getElementById('add-couriers-modal');
    const cancelAddCourierBtn = document.getElementById('cancel-add-courier');
    const closeAddCourierModalBtn = document.querySelector('#add-couriers-modal .close-modal');
    const addCourierForm = document.getElementById('add-courier-form');

    // 关闭按钮事件
    if (cancelAddCourierBtn) {
        cancelAddCourierBtn.addEventListener('click', closeAddCourierModal);
    }

    // 关闭模态框事件
    if (closeAddCourierModalBtn) {
        closeAddCourierModalBtn.addEventListener('click', closeAddCourierModal);
    }

    // 点击模态框外部关闭
    window.addEventListener('click', function (event) {
        if (event.target === addCourierModal) {
            closeAddCourierModal();
        }
    });

    // 表单提交事件
    if (addCourierForm) {
        addCourierForm.addEventListener('submit', function (event) {
            event.preventDefault();
            submitAddCourierForm();
        });
    }

    // 初始化添加用户模态框相关元素和事件

    // 初始化添加用户模态框相关元素和事件
    const addUserModal = document.getElementById('add-user-modal');
    const cancelAddUserBtn = document.getElementById('cancel-add-user');
    const closeAddModalBtn = document.querySelector('#add-user-modal .close-modal');
    const addUserForm = document.getElementById('add-user-form');

    // 关闭按钮事件
    if (cancelAddUserBtn) {
        cancelAddUserBtn.addEventListener('click', closeAddUserModal);
    }

    // 关闭模态框事件
    if (closeAddModalBtn) {
        closeAddModalBtn.addEventListener('click', closeAddUserModal);
    }

    // 点击模态框外部关闭
    window.addEventListener('click', function (event) {
        if (event.target === addUserModal) {
            closeAddUserModal();
        }
    });

    // 表单提交事件
    if (addUserForm) {
        addUserForm.addEventListener('submit', function (event) {
            event.preventDefault();
            submitAddUserForm();
        });
    }

    // 初始化查看用户模态框相关元素和事件
    const viewUserModal = document.getElementById('view-user-modal');
    const closeViewUserBtn = document.getElementById('close-view-user-modal');
    const closeViewModalBtn = document.querySelector('#view-user-modal .close-modal');

    // 关闭按钮事件
    if (closeViewUserBtn) {
        closeViewUserBtn.addEventListener('click', closeViewUserModal);
    }

    // 关闭模态框事件
    if (closeViewModalBtn) {
        closeViewModalBtn.addEventListener('click', closeViewUserModal);
    }

    // 点击模态框外部关闭
    window.addEventListener('click', function (event) {
        if (event.target === viewUserModal) {
            closeViewUserModal();
        }
    });

    // 为用户管理表格的查看按钮添加点击事件
    const userViewButtons = document.querySelectorAll('#users-tab .btn-view');
    userViewButtons.forEach(button => {
        button.addEventListener('click', function () {
            const userId = this.getAttribute('data-id');
            const username = this.getAttribute('data-username');
            const email = this.getAttribute('data-email');
            const phone = this.getAttribute('data-phone');
            const regtime = this.getAttribute('data-regtime');
            const status = this.getAttribute('data-status');
            const role = this.getAttribute('data-role');

            openViewUserModal(userId, username, email, phone, regtime, status, role);
        });
    });

    // 初始化编辑用户模态框相关元素和事件
    const editUserModal = document.getElementById('edit-user-modal');
    const closeEditModalBtn = document.querySelector('#edit-user-modal .close-modal');
    const cancelEditUserBtn = document.getElementById('cancel-edit-user');
    const editUserForm = document.getElementById('edit-user-form');

    // 关闭模态框事件
    if (closeEditModalBtn) {
        closeEditModalBtn.addEventListener('click', closeEditUserModal);
    }

    // 取消按钮事件
    if (cancelEditUserBtn) {
        cancelEditUserBtn.addEventListener('click', closeEditUserModal);
    }

    // 点击模态框外部关闭
    window.addEventListener('click', function (event) {
        if (event.target === editUserModal) {
            closeEditUserModal();
        }
    });

    // 表单提交事件
    if (editUserForm) {
        editUserForm.addEventListener('submit', function (event) {
            event.preventDefault();
            submitEditUserForm();
        });
    }

    // 为所有编辑按钮添加点击事件
    const editButtons = document.querySelectorAll('.btn-edit');
    editButtons.forEach(button => {
        button.addEventListener('click', function () {
            // 用户管理和物流员管理表格的编辑按钮
            if (this.hasAttribute('data-id') && this.hasAttribute('data-username')) {
                const userId = this.getAttribute('data-id');
                const username = this.getAttribute('data-username');
                const email = this.getAttribute('data-email');
                const phone = this.getAttribute('data-phone');
                const status = this.getAttribute('data-status');
                const role = this.getAttribute('data-role') || 'courier'; // 默认为物流员

                openEditUserModal(userId, username, email, phone, status, role);
            }
        });
    });

    // 为物流员表格中的查看按钮添加点击事件
    const courierViewButtons = document.querySelectorAll('#couriers-tab .btn-view');
    courierViewButtons.forEach(button => {
        button.addEventListener('click', function () {
            const courierId = this.getAttribute('data-id');
            const name = this.getAttribute('data-name');
            const phone = this.getAttribute('data-phone');
            const area = this.getAttribute('data-area');
            const email = this.getAttribute('data-email');
            const joinDate = this.getAttribute('data-join-date');
            const deliveryCount = this.getAttribute('data-delivery-count');
            const status = this.getAttribute('data-status');

            // 打开查看物流员模态框
            openViewCourierModal(courierId, name, phone, area, email, joinDate, deliveryCount, status);
        });
    });

    // 为物流员表格中的编辑按钮添加点击事件
    const courierEditButtons = document.querySelectorAll('#couriers-tab .btn-edit');
    courierEditButtons.forEach(button => {
        button.addEventListener('click', function () {
            const courierId = this.getAttribute('data-id');
            const name = this.getAttribute('data-name');
            const phone = this.getAttribute('data-phone');
            const area = this.getAttribute('data-area');
            const email = this.getAttribute('data-email');
            const status = this.getAttribute('data-status');

            // 打开编辑物流员模态框
            openEditCourierModal(courierId, name, phone, area, email, status);
        });
    });

    // 查看物流员模态框关闭按钮点击事件
    const closeViewCourierBtn = document.getElementById('close-view-courier-modal');
    if (closeViewCourierBtn) {
        closeViewCourierBtn.addEventListener('click', closeViewCourierModal);
    }

    // 编辑物流员模态框取消按钮点击事件
    const cancelEditCourierBtn = document.getElementById('cancel-edit-courier');
    if (cancelEditCourierBtn) {
        cancelEditCourierBtn.addEventListener('click', closeEditCourierModal);
    }

}

// 打开查看用户模态框
function openViewUserModal(userId, username, email, phone, regtime, status, role) {
    const viewUserModal = document.getElementById('view-user-modal');
    if (viewUserModal) {
        // 填充用户数据
        document.getElementById('view-user-id').textContent = userId;
        document.getElementById('view-username').textContent = username;
        document.getElementById('view-email').textContent = email;
        document.getElementById('view-phone').textContent = phone;
        document.getElementById('view-regtime').textContent = regtime;
        document.getElementById('view-status').textContent = status;
        document.getElementById('view-role').textContent = role;

        // 移除hidden类以显示模态框
        viewUserModal.classList.remove('hidden');
    }
}

// 关闭查看用户模态框
function closeViewUserModal() {
    const viewUserModal = document.getElementById('view-user-modal');
    if (viewUserModal) {
        // 添加hidden类以隐藏模态框
        viewUserModal.classList.add('hidden');
    }
}

// 打开编辑用户模态框
function openEditUserModal(userId, username, email, phone, status, role) {
    const editUserModal = document.getElementById('edit-user-modal');
    if (editUserModal) {
        // 填充用户数据
        document.getElementById('edit-user-id').value = userId;
        document.getElementById('edit-username').value = username;
        document.getElementById('edit-email').value = email;
        document.getElementById('edit-phone').value = phone;
        document.getElementById('edit-status').value = status;
        document.getElementById('edit-role').value = role;

        // 移除hidden类以显示模态框
        editUserModal.classList.remove('hidden');
    }
}

// 打开查看物流员模态框
function openViewCourierModal(courierId, name, phone, area, email, joinDate, deliveryCount, status) {
    const viewCourierModal = document.getElementById('view-couriers-modal');
    if (viewCourierModal) {
        // 填充物流员数据
        document.getElementById('view-courier-id').textContent = courierId;
        document.getElementById('view-courier-name').textContent = name;
        document.getElementById('view-courier-phone').textContent = phone;
        document.getElementById('view-courier-area').textContent = area;
        document.getElementById('view-courier-email').textContent = email;
        document.getElementById('view-courier-regtime').textContent = joinDate || '未知';
        document.getElementById('view-courier-deliveries').textContent = deliveryCount || '0';
        document.getElementById('view-courier-status').textContent = status || '离线';

        // 移除hidden类以显示模态框
        viewCourierModal.classList.remove('hidden');
        updateModalOverlay();
    }
}

// 关闭查看物流员模态框
function closeViewCourierModal() {
    const viewCourierModal = document.getElementById('view-couriers-modal');
    if (viewCourierModal) {
        viewCourierModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 打开编辑物流员模态框
function openEditCourierModal(courierId, name, phone, area, email, status) {
    const editCourierModal = document.getElementById('edit-couriers-modal');
    if (editCourierModal) {
        // 填充物流员数据
        document.getElementById('edit-courier-id').value = courierId;
        document.getElementById('edit-courier-name').value = name;
        document.getElementById('edit-courier-phone').value = phone;
        document.getElementById('edit-courier-area').value = area;
        document.getElementById('edit-courier-email').value = email;
        document.getElementById('edit-courier-status').value = status;

        // 移除hidden类以显示模态框
        editCourierModal.classList.remove('hidden');
        updateModalOverlay();
    }
}

// 关闭编辑物流员模态框
function closeEditCourierModal() {
    const editCourierModal = document.getElementById('edit-couriers-modal');
    if (editCourierModal) {
        editCourierModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 提交编辑物流员表单
function submitEditCourierForm() {
    const form = document.getElementById('edit-courier-form');
    if (!form) return;

    // 获取表单数据
    const courierId = document.getElementById('edit-courier-id').value;
    const name = document.getElementById('edit-courier-name').value.trim();
    const phone = document.getElementById('edit-courier-phone').value.trim();
    const status = document.getElementById('edit-courier-status').value;

    // 表单验证
    if (!name || !phone) {
        showTopNotification('请填写所有必填字段', 'error');
        return;
    }

    // 模拟API请求更新物流员
    console.log('提交编辑物流员表单:', {
        courierId,
        name,
        phone,
        status
    });

    // 关闭模态框
    closeEditCourierModal();

    // 显示成功通知
    showTopNotification('物流员信息已成功更新', 'success');
}

// 关闭编辑用户模态框
function closeEditUserModal() {
    const editUserModal = document.getElementById('edit-user-modal');
    if (editUserModal) {
        // 添加hidden类以隐藏模态框
        editUserModal.classList.add('hidden');
    }
}

// 提交编辑用户表单
function submitEditUserForm() {
    const form = document.getElementById('edit-user-form');
    if (!form) return;

    // 获取表单数据
    const userId = document.getElementById('edit-user-id').value;
    const username = document.getElementById('edit-username').value;
    const email = document.getElementById('edit-email').value;
    const phone = document.getElementById('edit-phone').value;
    const status = document.getElementById('edit-status').value;
    const role = document.getElementById('edit-role').value;

    // 模拟表单提交
    console.log('提交编辑用户表单:', {
        userId,
        username,
        email,
        phone,
        status,
        role
    });

    // 关闭模态框
    closeEditUserModal();

    // 显示成功通知
    showTopNotification('用户信息已成功更新', 'success');
}


// 初始化包裹管理相关事件
function initPackageEventListeners() {
    // 为包裹表格中的查看按钮添加点击事件
    const packageViewButtons = document.querySelectorAll('#packages-tab .btn-view');
    packageViewButtons.forEach(button => {
        button.addEventListener('click', function () {
            const trackingNumber = this.getAttribute('data-tracking-number') || '未知';
            const sender = this.getAttribute('data-sender') || '未知';
            const senderPhone = this.getAttribute('data-sender-phone') || '未知';
            const receiver = this.getAttribute('data-receiver') || '未知';
            const receiverPhone = this.getAttribute('data-receiver-phone') || '未知';
            const address = this.getAttribute('data-address') || '未知';
            const status = this.getAttribute('data-status') || '未知';
            const courier = this.getAttribute('data-courier') || '未知';
            const sendDate = this.getAttribute('data-send-date') || '未知';
            const estimatedDate = this.getAttribute('data-estimated-date') || '未知';
            const deliveryDate = this.getAttribute('data-delivery-date') || '未送达';

            // 打开查看包裹模态框
            openViewPackageModal(
                trackingNumber, sender, senderPhone, receiver, receiverPhone,
                address, status, courier, sendDate, estimatedDate, deliveryDate
            );
        });
    });

    // 为包裹表格中的编辑按钮添加点击事件
    const packageEditButtons = document.querySelectorAll('#packages-tab .btn-edit');
    packageEditButtons.forEach(button => {
        button.addEventListener('click', function () {
            const trackingNumber = this.getAttribute('data-tracking-number') || '未知';
            const sender = this.getAttribute('data-sender') || '未知';
            const senderPhone = this.getAttribute('data-sender-phone') || '未知';
            const receiver = this.getAttribute('data-receiver') || '未知';
            const receiverPhone = this.getAttribute('data-receiver-phone') || '未知';
            const address = this.getAttribute('data-address') || '未知';
            const status = this.getAttribute('data-status') || '未知';
            const courier = this.getAttribute('data-courier') || '未知';
            const sendDate = this.getAttribute('data-send-date') || '未知';
            const estimatedDate = this.getAttribute('data-estimated-date') || '未知';

            // 打开编辑包裹模态框
            openEditPackageModal(
                trackingNumber, sender, senderPhone, receiver, receiverPhone,
                address, status, courier, sendDate, estimatedDate
            );
        });
    });

    // 包裹详情模态框关闭按钮点击事件
    const closeViewPackageBtn = document.getElementById('close-view-package-modal');
    if (closeViewPackageBtn) {
        closeViewPackageBtn.addEventListener('click', closeViewPackageModal);
    }

    // 编辑包裹模态框关闭按钮点击事件
    const closeEditPackageBtn = document.getElementById('close-edit-package-modal');
    if (closeEditPackageBtn) {
        closeEditPackageBtn.addEventListener('click', closeEditPackageModal);
    }

    // 取消编辑包裹按钮点击事件
    const cancelEditPackageBtn = document.getElementById('cancel-edit-package');
    if (cancelEditPackageBtn) {
        cancelEditPackageBtn.addEventListener('click', closeEditPackageModal);
    }

    // 编辑包裹表单提交事件
    const editPackageForm = document.getElementById('edit-package-form');
    if (editPackageForm) {
        editPackageForm.addEventListener('submit', function (event) {
            event.preventDefault();
            submitEditPackageForm();
        });
    }
}

// 打开编辑包裹模态框
function openEditPackageModal(trackingNumber, sender, senderPhone, receiver, receiverPhone, address, status, courier, sendDate, estimatedDate) {
    const editPackageModal = document.getElementById('edit-packages-modal');
    if (editPackageModal) {
        // 填充包裹数据
        document.getElementById('edit-package-tracking-number').value = trackingNumber;
        document.getElementById('edit-package-sender').value = sender;
        document.getElementById('edit-package-sender-phone').value = senderPhone;
        document.getElementById('edit-package-receiver').value = receiver;
        document.getElementById('edit-package-receiver-phone').value = receiverPhone;
        document.getElementById('edit-package-address').value = address;
        document.getElementById('edit-package-status').value = status;
        document.getElementById('edit-package-courier').value = courier;
        document.getElementById('edit-package-send-date').value = sendDate;
        document.getElementById('edit-package-estimated-date').value = estimatedDate;

        // 移除hidden类以显示模态框
        editPackageModal.classList.remove('hidden');
        updateModalOverlay();
    }
}

// 关闭编辑包裹模态框
function closeEditPackageModal() {
    const editPackageModal = document.getElementById('edit-packages-modal');
    if (editPackageModal) {
        editPackageModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 提交编辑包裹表单
function submitEditPackageForm() {
    const form = document.getElementById('edit-package-form');
    if (!form) return;

    // 获取表单数据
    const trackingNumber = document.getElementById('edit-package-tracking-number').value;
    const sender = document.getElementById('edit-package-sender').value.trim();
    const senderPhone = document.getElementById('edit-package-sender-phone').value.trim();
    const receiver = document.getElementById('edit-package-receiver').value.trim();
    const receiverPhone = document.getElementById('edit-package-receiver-phone').value.trim();
    const address = document.getElementById('edit-package-address').value.trim();
    const status = document.getElementById('edit-package-status').value;
    const courier = document.getElementById('edit-package-courier').value;
    const sendDate = document.getElementById('edit-package-send-date').value;
    const estimatedDate = document.getElementById('edit-package-estimated-date').value;

    // 表单验证
    if (!sender || !senderPhone || !receiver || !receiverPhone || !address) {
        showTopNotification('请填写所有必填字段', 'error');
        return;
    }

    // 模拟API请求更新包裹
    console.log('提交编辑包裹表单:', {
        trackingNumber,
        sender,
        senderPhone,
        receiver,
        receiverPhone,
        address,
        status,
        courier,
        sendDate,
        estimatedDate
    });

    // 关闭模态框
    closeEditPackageModal();

    // 显示成功通知
    showTopNotification('包裹信息已成功更新', 'success');
}

// 打开查看包裹模态框
function openViewPackageModal(trackingNumber, sender, senderPhone, receiver, receiverPhone, address, status, courier, sendDate, estimatedDate, deliveryDate) {
    const viewPackageModal = document.getElementById('view-packages-modal');
    if (viewPackageModal) {
        // 填充包裹数据
        document.getElementById('view-package-tracking-number').textContent = trackingNumber;
        document.getElementById('view-package-sender').textContent = sender;
        document.getElementById('view-package-sender-phone').textContent = senderPhone;
        document.getElementById('view-package-receiver').textContent = receiver;
        document.getElementById('view-package-receiver-phone').textContent = receiverPhone;
        document.getElementById('view-package-address').textContent = address;
        document.getElementById('view-package-status').textContent = status;
        document.getElementById('view-package-courier').textContent = courier;
        document.getElementById('view-package-send-date').textContent = sendDate;
        document.getElementById('view-package-estimated-date').textContent = estimatedDate;
        document.getElementById('view-package-delivery-date').textContent = deliveryDate;

        // 移除hidden类以显示模态框
        viewPackageModal.classList.remove('hidden');
        updateModalOverlay();
    }
}

// 关闭查看包裹模态框
function closeViewPackageModal() {
    const viewPackageModal = document.getElementById('view-packages-modal');
    if (viewPackageModal) {
        viewPackageModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 更新模态框显示状态时控制背景遮罩
function updateModalOverlay() {
    const modals = document.querySelectorAll('.modal');
    let anyModalVisible = false;

    modals.forEach(modal => {
        if (!modal.classList.contains('hidden')) {
            anyModalVisible = true;
        }
    });

    if (modalOverlay) {
        if (anyModalVisible) {
            modalOverlay.classList.remove('hidden');
        } else {
            modalOverlay.classList.add('hidden');
        }
    }
}

// 显示/隐藏加载状态
function showLoading(show) {
    const loadingIndicator = document.getElementById('loading-indicator');
    
    if (!loadingIndicator) return;
    
    if (show) {
        loadingIndicator.classList.remove('hidden');
        // 更新模态框背景遮罩
        updateModalOverlay();
    } else {
        loadingIndicator.classList.add('hidden');
    }
}

// 显示顶部通知卡片
function showTopNotification(message, type = 'info') {
    const notification = document.getElementById('top-notification');
    const messageEl = document.getElementById('notification-message');

    if (!notification || !messageEl) return;

    // 设置消息内容
    messageEl.textContent = message;

    // 移除所有类型类
    notification.classList.remove('success', 'error', 'info');

    // 添加类型类
    if (type === 'success' || type === 'error') {
        notification.classList.add(type);
    }

    // 显示通知
    notification.classList.remove('hidden');
    // 更新模态框背景遮罩
    updateModalOverlay();

    // 设置自动隐藏
    setTimeout(hideTopNotification, 3000);
}

// 隐藏顶部通知卡片
function hideTopNotification() {
    const notification = document.getElementById('top-notification');
    if (notification) {
        notification.classList.add('hidden');
    }
}

// 为所有模态框的关闭按钮添加事件
function initModalCloseButtons() {
    // 为所有带.close-modal类的元素添加点击事件
    const closeModalButtons = document.querySelectorAll('.close-modal');
    closeModalButtons.forEach(button => {
        button.addEventListener('click', function () {
                // 找到最近的模态框
                const modal = this.closest('.modal');
                if (modal) {
                    modal.classList.add('hidden');
                    updateModalOverlay();
                }
            }
        );
    });
}

// 关闭添加角色模态框
function closeAddRoleModal() {
    console.log('closeAddRoleModal function called');
    const addRoleModal = document.getElementById('add-roles-modal');
    if (addRoleModal) {
        console.log('Hiding add role modal');
        addRoleModal.classList.add('hidden');
        updateModalOverlay();
    } else {
        console.log('add-roles-modal not found');
    }
}

// 初始化角色数据
function loadRolesData() {
    console.log('加载角色数据...');
    // 显示加载状态
    showLoading(true);
    
    // 使用API服务获取角色数据
    apiService.fetch('/api/roles', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(response => {
        // 隐藏加载状态
        showLoading(false);
        
        if (response.success) {
            console.log('角色数据加载成功:', response.data);
            // 填充角色表格
            populateRoleTable(response.data);
        } else {
            console.error('加载角色数据失败:', response.message);
            showTopNotification('加载角色数据失败: ' + (response.message || '未知错误'), 'error');
        }
    }).catch(error => {
        // 隐藏加载状态
        showLoading(false);
        
        console.error('加载角色数据时发生错误:', error);
        showTopNotification('加载角色数据时发生错误，请稍后再试', 'error');
    });
}

// 填充角色表格
function populateRoleTable(roles) {
    console.log('填充角色表格...');
    // 获取角色表格tbody元素
    const tableBody = document.querySelector('#roles-tab table tbody');
    
    if (!tableBody) {
        console.error('未找到角色表格 tbody 元素');
        return;
    }
    
    // 清空表格内容
    tableBody.innerHTML = '';
    
    // 检查角色数据是否为空
    if (!roles || roles.length === 0) {
        // 显示无数据提示
        const emptyRow = document.createElement('tr');
        emptyRow.innerHTML = `<td colspan="4" class="text-center py-4">暂无角色数据</td>`;
        tableBody.appendChild(emptyRow);
        return;
    }
    
    // 遍历角色数据并添加到表格
    roles.forEach(role => {
        const row = document.createElement('tr');
        
        // 构建权限显示文本
        const permissionText = role.permissions.map(perm => {
            const permMap = {
                'user_management': '用户管理',
                'courier_management': '物流员管理',
                'package_management': '包裹管理',
                'route_management': '路线管理',
                'role_management': '角色管理',
                'exception_handling': '异常处理'
            };
            return permMap[perm] || perm;
        }).join('，');
        
        // 设置行内容
        row.innerHTML = `
            <td>${role.name}</td>
            <td>${role.description}</td>
            <td>${role.userCount}</td>
            <td class="action-buttons">
                <button class="btn-view" data-role-id="${role.id}" data-name="${role.name}" data-description="${role.description}" data-user-count="${role.userCount}" data-permissions="${role.permissions.join(',')}"><i class="fas fa-eye"></i></button>
                <button class="btn-edit" data-role-id="${role.id}" data-name="${role.name}" data-description="${role.description}" data-permissions="${role.permissions.join(',')}"><i class="fas fa-edit"></i></button>
                <button class="btn-delete" data-role-id="${role.id}" data-name="${role.name}" data-user-count="${role.userCount}"><i class="fas fa-trash-alt"></i></button>
            </td>
        `;
        
        tableBody.appendChild(row);
    });
    
    // 绑定表格按钮事件
    bindRoleTableButtons();
}
// 绑定角色表格按钮事件
function bindRoleTableButtons() {
    // 先移除已有的事件监听器
    const oldViewButtons = document.querySelectorAll('#roles-tab .btn-view');
    oldViewButtons.forEach(button => {
        const clone = button.cloneNode(true);
        button.parentNode.replaceChild(clone, button);
    });
    
    const oldEditButtons = document.querySelectorAll('#roles-tab .btn-edit');
    oldEditButtons.forEach(button => {
        const clone = button.cloneNode(true);
        button.parentNode.replaceChild(clone, button);
    });
    
    const oldDeleteButtons = document.querySelectorAll('#roles-tab .btn-delete');
    oldDeleteButtons.forEach(button => {
        const clone = button.cloneNode(true);
        button.parentNode.replaceChild(clone, button);
    });
    
    // 为角色表格中的查看按钮添加点击事件
    const roleViewButtons = document.querySelectorAll('#roles-tab .btn-view');
    roleViewButtons.forEach(button => {
        button.addEventListener('click', function () {
            const roleName = this.getAttribute('data-name');
            const roleDescription = this.getAttribute('data-description');
            const userCount = this.getAttribute('data-user-count');
            const permissions = this.getAttribute('data-permissions') ? this.getAttribute('data-permissions').split(',') : [];

            // 打开查看角色模态框
            openViewRoleModal(roleName, roleDescription, userCount, permissions);
        });
    });

    // 为角色表格中的编辑按钮添加点击事件
    const roleEditButtons = document.querySelectorAll('#roles-tab .btn-edit');
    roleEditButtons.forEach(button => {
        button.addEventListener('click', function () {
            const roleId = this.getAttribute('data-role-id');
            const roleName = this.getAttribute('data-name');
            const roleDescription = this.getAttribute('data-description');
            const permissions = this.getAttribute('data-permissions') ? this.getAttribute('data-permissions').split(',') : [];

            // 打开编辑角色模态框
            openEditRoleModal(roleId, roleName, roleDescription, permissions);
        });
    });
    
    // 为角色表格中的删除按钮添加点击事件
    const roleDeleteButtons = document.querySelectorAll('#roles-tab .btn-delete');
    roleDeleteButtons.forEach(button => {
        button.addEventListener('click', function () {
            const roleId = this.getAttribute('data-role-id');
            const roleName = this.getAttribute('data-name');
            const userCount = this.getAttribute('data-user-count');

            // 打开删除角色模态框
            openDeleteRoleModal(roleId, roleName, userCount);
        });
    });
}

// 初始化角色管理相关事件
function initRoleEventListeners() {
    console.log('initRoleEventListeners function called');
    // 为添加角色模态框的取消按钮添加点击事件
    const cancelAddRoleBtn = document.getElementById('cancel-add-role');
    if (cancelAddRoleBtn) {
        console.log('cancel-add-role button found, adding event listener');
        cancelAddRoleBtn.addEventListener('click', closeAddRoleModal);
    } else {
        console.log('cancel-add-role button not found');
    }

    // 添加角色表单提交事件
    const addRoleForm = document.getElementById('add-role-form');
    if (addRoleForm) {
        addRoleForm.addEventListener('submit', submitAddRoleForm);
    }

    // 查看角色模态框关闭按钮点击事件
    const closeViewRoleBtn = document.getElementById('close-view-role-modal');
    if (closeViewRoleBtn) {
        closeViewRoleBtn.addEventListener('click', closeViewRoleModal);
    }

    // 编辑角色模态框关闭按钮点击事件
    const closeEditRoleBtn = document.getElementById('close-edit-role-modal');
    if (closeEditRoleBtn) {
        closeEditRoleBtn.addEventListener('click', closeEditRoleModal);
    }

    // 取消编辑角色按钮点击事件
    const cancelEditRoleBtn = document.getElementById('cancel-edit-role');
    if (cancelEditRoleBtn) {
        cancelEditRoleBtn.addEventListener('click', closeEditRoleModal);
    }

    // 编辑角色表单提交事件
    const editRoleForm = document.getElementById('edit-role-form');
    if (editRoleForm) {
        editRoleForm.addEventListener('submit', function (event) {
            event.preventDefault();
            submitEditRoleForm();
        });
    }

    // 删除角色模态框关闭按钮点击事件
    const closeDeleteRoleBtn = document.getElementById('close-delete-role-modal');
    if (closeDeleteRoleBtn) {
        closeDeleteRoleBtn.addEventListener('click', closeDeleteRoleModal);
    }

    // 取消删除角色按钮点击事件
    const cancelDeleteRoleBtn = document.getElementById('cancel-delete-role');
    if (cancelDeleteRoleBtn) {
        cancelDeleteRoleBtn.addEventListener('click', closeDeleteRoleModal);
    }

    // 删除角色表单提交事件
    const deleteRoleForm = document.getElementById('delete-role-form');
    if (deleteRoleForm) {
        deleteRoleForm.addEventListener('submit', function (event) {
            event.preventDefault();
            submitDeleteRoleForm();
        });
    }
}

// 打开查看角色模态框
function openViewRoleModal(roleName, roleDescription, userCount, permissions) {
    const viewRoleModal = document.getElementById('view-roles-modal');
    if (viewRoleModal) {
        // 填充角色数据
        document.getElementById('view-role-name').textContent = roleName || '未知';
        document.getElementById('view-role-description').textContent = roleDescription || '无描述';
        document.getElementById('view-role-user-count').textContent = userCount || '0';

        // 清空并填充权限列表
        const permissionsList = document.getElementById('view-role-permissions');
        if (permissionsList) {
            permissionsList.innerHTML = '';
            permissions.forEach(permission => {
                const li = document.createElement('li');
                // 权限名称格式化（将下划线转为空格并首字母大写）
                const formattedPermission = permission.replace('_', ' ').replace(/\b\w/g, c => c.toUpperCase());
                li.textContent = formattedPermission;
                permissionsList.appendChild(li);
            });
        }

        // 移除hidden类以显示模态框
        viewRoleModal.classList.remove('hidden');
        updateModalOverlay();
    }
}

// 关闭查看角色模态框
function closeViewRoleModal() {
    const viewRoleModal = document.getElementById('view-roles-modal');
    if (viewRoleModal) {
        viewRoleModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 打开编辑角色模态框
function openEditRoleModal(roleName, roleDescription, permissions) {
    const editRoleModal = document.getElementById('edit-roles-modal');
    if (editRoleModal) {
        // 填充角色数据
        document.getElementById('edit-role-name').value = roleName || '';
        document.getElementById('edit-role-description').value = roleDescription || '';

        // 重置所有权限复选框
        document.querySelectorAll('#edit-roles-modal input[type="checkbox"]').forEach(checkbox => {
            checkbox.checked = false;
        });

        // 勾选相应的权限
        permissions.forEach(permission => {
            const checkbox = document.getElementById(`edit-perm-${permission}`);
            if (checkbox) {
                checkbox.checked = true;
            }
        });

        // 移除hidden类以显示模态框
        editRoleModal.classList.remove('hidden');
        updateModalOverlay();
    }
}

// 关闭编辑角色模态框
function closeEditRoleModal() {
    const editRoleModal = document.getElementById('edit-roles-modal');
    if (editRoleModal) {
        editRoleModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 提交编辑角色表单
function submitEditRoleForm() {
    console.log('---------- submitEditRoleForm函数开始执行 ----------');
    const form = document.getElementById('edit-role-form');
    if (!form) {
        console.log('edit-role-form未找到');
        return;
    }

    // 获取表单数据
    const roleName = document.getElementById('edit-role-name').value.trim();
    const roleDescription = document.getElementById('edit-role-description').value.trim();
    console.log('角色名称:', roleName, '角色描述:', roleDescription);

    // 收集选中的权限
    let permissions = [];
    console.log(' permissions变量已初始化:', permissions);
    console.log('开始收集权限...');
    const checkboxes = document.querySelectorAll('#edit-roles-modal input[name="permissions"]:checked');
    console.log('找到的复选框数量:', checkboxes.length);
    checkboxes.forEach(checkbox => {
        permissions.push(checkbox.value);
        console.log('添加权限:', checkbox.value);
    });
    
    console.log('收集到的权限:', permissions);
    console.log('permissions变量类型:', typeof permissions);
    console.log('permissions变量是否存在:', permissions !== undefined);

    // 表单验证
    if (!roleName) {
        showTopNotification('角色名称不能为空', 'error');
        console.log('表单验证失败，返回');
        return;
    }

    console.log('表单验证通过，准备提交');
    // 模拟API请求更新角色
    console.log('提交编辑角色表单:', {
        roleName,
        roleDescription,
        permissions
    });

    // 关闭模态框
    closeEditRoleModal();

    // 显示成功通知
    showTopNotification('角色信息已成功更新', 'success');
}

// 已将权限列表填充逻辑移至openViewRoleModal函数中

// 关闭查看角色模态框
function closeViewRoleModal() {
    const viewRoleModal = document.getElementById('view-roles-modal');
    if (viewRoleModal) {
        viewRoleModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 页面加载完成后初始化
window.addEventListener('load', function () {
    // 初始化所有模态框关闭按钮
    initModalCloseButtons();
    // 初始化角色管理相关事件
    initRoleEventListeners();
    // 初始化路线管理相关事件
    initRouteEventListeners();
    // 初始化异常处理相关事件
    initExceptionEventListeners();
});

// 测试按钮点击的简单函数
function testButtonClick() {
    alert('按钮点击事件被触发！');
    console.log('按钮点击事件被触发');
}

// 初始化异常处理相关事件
function initExceptionEventListeners() {
    console.log('initExceptionEventListeners函数被调用');
    // 为异常表格中的查看按钮添加点击事件
    function bindExceptionViewButtons() {
        const exceptionViewButtons = document.querySelectorAll('#exceptions-tab .btn-view');
        console.log('查找的异常查看按钮数量:', exceptionViewButtons.length);
        if (exceptionViewButtons.length > 0) {
            exceptionViewButtons.forEach(button => {
                // 移除可能存在的旧事件监听器
                button.removeEventListener('click', handleExceptionViewClick);
                // 添加新的点击事件处理程序
                button.addEventListener('click', handleExceptionViewClick);
            });
            console.log('异常查看按钮事件已绑定');
        } else {
            console.error('未找到异常查看按钮，将在1秒后重试');
            // 如果未找到按钮，1秒后重试
            setTimeout(bindExceptionViewButtons, 1000);
        }
    }
    
    // 为异常表格中的编辑按钮添加点击事件
    function bindExceptionEditButtons() {
        const exceptionEditButtons = document.querySelectorAll('#exceptions-tab .btn-edit');
        console.log('查找的异常编辑按钮数量:', exceptionEditButtons.length);
        if (exceptionEditButtons.length > 0) {
            exceptionEditButtons.forEach(button => {
                // 移除可能存在的旧事件监听器
                button.removeEventListener('click', handleExceptionEditClick);
                // 添加新的点击事件处理程序
                button.addEventListener('click', handleExceptionEditClick);
            });
            console.log('异常编辑按钮事件已绑定');
        } else {
            console.error('未找到异常编辑按钮，将在1秒后重试');
            // 如果未找到按钮，1秒后重试
            setTimeout(bindExceptionEditButtons, 1000);
        }
    }
    
    function handleExceptionViewClick() {
        console.log('异常查看按钮被点击');
        // 获取按钮上的data属性值
        const trackingNumber = this.getAttribute('data-tracking-number');
        const exceptionType = this.getAttribute('data-type');
        const exceptionTime = this.getAttribute('data-time');
        const exceptionStatus = this.getAttribute('data-status');
        const exceptionDescription = this.getAttribute('data-description');
        const handlingRecords = this.getAttribute('data-handling-records') || '[]';
        
        console.log('运单编号:', trackingNumber);
        console.log('异常类型:', exceptionType);
        
        // 显示模态框
        const modal = document.getElementById('view-exceptions-modal');
        if (modal) {
            // 填充模态框数据
            document.getElementById('view-exception-tracking-number').textContent = trackingNumber || '未知';
            document.getElementById('view-exception-type').textContent = exceptionType || '未知';
            document.getElementById('view-exception-time').textContent = exceptionTime || '未知';
            document.getElementById('view-exception-status').textContent = exceptionStatus || '未知';
            document.getElementById('view-exception-description').textContent = exceptionDescription || '无';
            
            // 填充处理记录
            const recordsContainer = document.getElementById('view-exception-handling-records');
            if (recordsContainer) {
                try {
                    const records = JSON.parse(handlingRecords);
                    if (records.length > 0) {
                        let recordsHtml = '<ul>';
                        records.forEach(record => {
                            recordsHtml += `<li>${record.time}: ${record.note} (处理人: ${record.handler || '系统'})</li>`;
                        });
                        recordsHtml += '</ul>';
                        recordsContainer.innerHTML = recordsHtml;
                    } else {
                        recordsContainer.innerHTML = '<p>暂无处理记录</p>';
                    }
                } catch (e) {
                    console.error('解析处理记录失败:', e);
                    recordsContainer.innerHTML = '<p>处理记录格式错误</p>';
                }
            }
            
            // 显示模态框
            modal.classList.remove('hidden');
            updateModalOverlay();
            console.log('异常详情模态框已显示');
        } else {
            console.error('未找到异常详情模态框元素');
        }
    }
    
    function handleExceptionEditClick() {
        console.log('异常编辑按钮被点击');
        // 获取按钮上的data属性值
        const exceptionId = this.getAttribute('data-id') || 'unknown';
        const trackingNumber = this.getAttribute('data-tracking-number');
        const exceptionType = this.getAttribute('data-type');
        const exceptionStatus = this.getAttribute('data-status');
        const exceptionDescription = this.getAttribute('data-description');
        
        console.log('异常ID:', exceptionId);
        console.log('运单编号:', trackingNumber);
        
        // 打开编辑异常模态框
        openEditExceptionModal(exceptionId, trackingNumber, exceptionType, exceptionStatus, exceptionDescription);
    }
    
    // 立即尝试绑定按钮事件
    bindExceptionViewButtons();
    bindExceptionEditButtons();

    // 查看异常模态框关闭按钮事件将在后面初始化
    // 此处不再重复处理
    
    // 初始化编辑异常模态框关闭按钮事件
    const closeEditExceptionButton = document.getElementById('close-edit-exception-modal');
    if (closeEditExceptionButton) {
        closeEditExceptionButton.addEventListener('click', closeEditExceptionModal);
    }
    
    // 初始化取消编辑异常按钮事件
    const cancelEditExceptionButton = document.getElementById('cancel-edit-exception');
    if (cancelEditExceptionButton) {
        cancelEditExceptionButton.addEventListener('click', closeEditExceptionModal);
    }
    
    // 初始化编辑异常表单提交事件
    const editExceptionForm = document.getElementById('edit-exception-form');
    if (editExceptionForm) {
        editExceptionForm.addEventListener('submit', function (event) {
            event.preventDefault();
            submitEditExceptionForm();
        });
    }
}

// 打开编辑异常模态框
function openEditExceptionModal(exceptionId, trackingNumber, exceptionType, exceptionStatus, exceptionDescription) {
    console.log('尝试打开编辑异常模态框');
    const editExceptionModal = document.getElementById('edit-exceptions-modal');
    if (editExceptionModal) {
        console.log('找到编辑异常模态框');
        
        // 填充表单数据
        document.getElementById('edit-exception-id').value = exceptionId;
        document.getElementById('edit-exception-type').value = exceptionType || 'other';
        document.getElementById('edit-exception-status').value = exceptionStatus || 'pending';
        document.getElementById('edit-exception-description').value = exceptionDescription || '';
        document.getElementById('edit-exception-handling-note').value = '';
        
        // 显示模态框
        editExceptionModal.classList.remove('hidden');
        updateModalOverlay();
        console.log('编辑异常模态框已显示');
    } else {
        console.error('未找到编辑异常模态框元素');
    }
}

// 关闭编辑异常模态框
function closeEditExceptionModal() {
    const editExceptionModal = document.getElementById('edit-exceptions-modal');
    if (editExceptionModal) {
        editExceptionModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 提交编辑异常表单
function submitEditExceptionForm() {
    console.log('提交编辑异常表单');
    const form = document.getElementById('edit-exception-form');
    if (!form) {
        console.error('未找到编辑异常表单');
        return;
    }
    
    // 获取表单数据
    const exceptionId = document.getElementById('edit-exception-id').value;
    const exceptionType = document.getElementById('edit-exception-type').value;
    const exceptionStatus = document.getElementById('edit-exception-status').value;
    const exceptionDescription = document.getElementById('edit-exception-description').value.trim();
    const handlingNote = document.getElementById('edit-exception-handling-note').value.trim();
    
    // 简单验证
    if (!exceptionId || !exceptionType || !exceptionStatus || !exceptionDescription) {
        console.error('表单数据不完整');
        showNotification('请填写所有必填字段', 'error');
        return;
    }
    
    // 构建请求数据
    const data = {
        id: exceptionId,
        type: exceptionType,
        status: exceptionStatus,
        description: exceptionDescription,
        handlingNote: handlingNote,
        handledAt: new Date().toISOString()
    };
    
    console.log('提交的异常数据:', data);
    
    // 发送API请求到服务器
    api.updateException(exceptionId, data)
        .then(response => {
            console.log('异常处理成功:', response);
            showNotification('异常处理成功', 'success');
            closeEditExceptionModal();
            // 刷新异常列表
            if (typeof loadExceptionsData === 'function') {
                loadExceptionsData();
            }
        })
        .catch(error => {
            console.error('异常处理失败:', error);
            showNotification('异常处理失败: ' + (error.message || '未知错误'), 'error');
        });
}

// 关闭查看异常模态框
function closeViewExceptionModal() {
    const viewExceptionModal = document.getElementById('view-exceptions-modal');
    if (viewExceptionModal) {
        viewExceptionModal.classList.add('hidden');
        updateModalOverlay();
    }
}
    console.log('initExceptionEventListeners函数被调用');
    // 为异常表格中的查看按钮添加点击事件
    function bindExceptionViewButtons() {
        const exceptionViewButtons = document.querySelectorAll('#exceptions-tab .btn-view');
        console.log('查找的异常查看按钮数量:', exceptionViewButtons.length);
        if (exceptionViewButtons.length > 0) {
            exceptionViewButtons.forEach(button => {
                // 移除可能存在的旧事件监听器
                button.removeEventListener('click', handleExceptionViewClick);
                // 添加新的点击事件处理程序
                button.addEventListener('click', handleExceptionViewClick);
            });
            console.log('异常查看按钮事件已绑定');
        } else {
            console.error('未找到异常查看按钮，将在1秒后重试');
            // 如果未找到按钮，1秒后重试
            setTimeout(bindExceptionViewButtons, 1000);
        }
    }
    
    function handleExceptionViewClick() {
        console.log('异常查看按钮被点击');
        // 获取按钮上的data属性值
        const trackingNumber = this.getAttribute('data-tracking-number');
        const exceptionType = this.getAttribute('data-type');
        const exceptionTime = this.getAttribute('data-time');
        const exceptionStatus = this.getAttribute('data-status');
        const exceptionDescription = this.getAttribute('data-description');
        const handlingRecords = this.getAttribute('data-handling-records') || '[]';
        
        console.log('运单编号:', trackingNumber);
        console.log('异常类型:', exceptionType);
        
        // 显示模态框
        const modal = document.getElementById('view-exceptions-modal');
        if (modal) {
            // 填充模态框数据
            document.getElementById('view-exception-tracking-number').textContent = trackingNumber || '未知';
            document.getElementById('view-exception-type').textContent = exceptionType || '未知';
            document.getElementById('view-exception-time').textContent = exceptionTime || '未知';
            document.getElementById('view-exception-status').textContent = exceptionStatus || '未知';
            document.getElementById('view-exception-description').textContent = exceptionDescription || '无';
            
            // 填充处理记录
            const recordsContainer = document.getElementById('view-exception-handling-records');
            if (recordsContainer) {
                try {
                    const records = JSON.parse(handlingRecords);
                    if (records.length > 0) {
                        let recordsHtml = '<ul>';
                        records.forEach(record => {
                            recordsHtml += `<li>${record.time}: ${record.note} (处理人: ${record.handler || '系统'})</li>`;
                        });
                        recordsHtml += '</ul>';
                        recordsContainer.innerHTML = recordsHtml;
                    } else {
                        recordsContainer.innerHTML = '<p>暂无处理记录</p>';
                    }
                } catch (e) {
                    console.error('解析处理记录失败:', e);
                    recordsContainer.innerHTML = '<p>处理记录格式错误</p>';
                }
            }
            
            // 显示模态框
            modal.classList.remove('hidden');
            updateModalOverlay();
            console.log('异常详情模态框已显示');
        } else {
            console.error('未找到异常详情模态框元素');
        }
    }
    
    // 立即尝试绑定按钮事件
    bindExceptionViewButtons();

    // 初始化查看异常模态框关闭按钮事件
    if (typeof closeViewExceptionButton === 'undefined') {
        const closeViewExceptionButton = document.getElementById('close-view-exception-modal');
        if (closeViewExceptionButton) {
            closeViewExceptionButton.addEventListener('click', closeViewExceptionModal);
        }
    } else if (closeViewExceptionButton) {
        // 确保事件只绑定一次
        if (!closeViewExceptionButton.dataset.eventBound) {
            closeViewExceptionButton.addEventListener('click', closeViewExceptionModal);
            closeViewExceptionButton.dataset.eventBound = 'true';
        }
    }


// 关闭查看异常模态框
function closeViewExceptionModal() {
    const viewExceptionModal = document.getElementById('view-exceptions-modal');
    if (viewExceptionModal) {
        viewExceptionModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 初始化路线管理相关事件
function initRouteEventListeners() {
    console.log('initRouteEventListeners函数被调用');
    console.log('initRouteEventListeners function called');
    // 初始化添加路线按钮事件
    const addRouteButton = document.querySelector('#routes-tab .add-button');
    if (addRouteButton) {
        console.log('找到添加路线按钮，准备绑定事件');
        addRouteButton.addEventListener('click', function (event) {
            event.preventDefault();
            console.log('添加路线按钮被点击');
            openAddRouteModal();
        });
        console.log('添加路线按钮事件已绑定');
    } else {
        console.log('未找到添加路线按钮');
    }

    // 为路线表格中的查看按钮添加点击事件
    function bindRouteViewButtons() {
        const routeViewButtons = document.querySelectorAll('#routes-tab .btn-view');
        console.log('查找的查看按钮数量:', routeViewButtons.length);
        if (routeViewButtons.length > 0) {
            routeViewButtons.forEach(button => {
                // 移除可能存在的旧事件监听器
                button.removeEventListener('click', handleRouteViewClick);
                // 添加新的点击事件处理程序
                button.addEventListener('click', handleRouteViewClick);
            });
            console.log('查看按钮事件已绑定');
        } else {
            console.error('未找到查看按钮，将在1秒后重试');
            // 如果未找到按钮，1秒后重试
            setTimeout(bindRouteViewButtons, 1000);
        }
    }
    
    function handleRouteViewClick() {
        console.log('查看按钮被点击');
        // 获取按钮上的data属性值
        const routeId = this.getAttribute('data-id');
        const routeName = this.getAttribute('data-name');
        const routeStart = this.getAttribute('data-start-point');
        const routeEnd = this.getAttribute('data-end-point');
        const routeCourier = this.getAttribute('data-courier');
        const routeEstimatedTime = this.getAttribute('data-estimated-time');
        const routeDescription = this.getAttribute('data-description');
        const routeCreatedTime = this.getAttribute('data-created-time');
        const routeUpdatedTime = this.getAttribute('data-updated-time');
        
        console.log('路线ID:', routeId);
        console.log('路线名称:', routeName);
        
        // 显示模态框
        const modal = document.getElementById('view-routes-modal');
        if (modal) {
            // 填充模态框数据
            document.getElementById('view-route-name').textContent = routeName || '未知';
            document.getElementById('view-route-start').textContent = routeStart || '未知';
            document.getElementById('view-route-end').textContent = routeEnd || '未知';
            document.getElementById('view-route-courier').textContent = routeCourier || '未知';
            document.getElementById('view-route-estimated-time').textContent = (routeEstimatedTime || '未知') + ' 分钟';
            document.getElementById('view-route-description').textContent = routeDescription || '无';
            document.getElementById('view-route-created-time').textContent = routeCreatedTime || '未知';
            document.getElementById('view-route-updated-time').textContent = routeUpdatedTime || '未知';
            
            // 显示模态框
            modal.classList.remove('hidden');
            updateModalOverlay();
            console.log('模态框已显示');
        } else {
            console.error('未找到模态框元素');
        }
    }
    
    // 立即尝试绑定按钮事件
    bindRouteViewButtons();

    // 初始化取消添加路线按钮事件
    const cancelAddRouteButton = document.getElementById('cancel-add-route');
    if (cancelAddRouteButton) {
        cancelAddRouteButton.addEventListener('click', closeAddRouteModal);
    }

    // 初始化添加路线表单提交事件
    const addRouteForm = document.getElementById('add-route-form');
    if (addRouteForm) {
        addRouteForm.addEventListener('submit', function (event) {
            event.preventDefault();
            submitAddRouteForm();
        });
    }

    // 初始化查看路线模态框关闭按钮事件
    const closeViewRouteButton = document.getElementById('close-view-route-modal');
    if (closeViewRouteButton) {
        closeViewRouteButton.addEventListener('click', closeViewRouteModal);
    }

    // 为路线表格中的编辑按钮添加点击事件
    const routeEditButtons = document.querySelectorAll('#routes-tab .btn-edit');
    routeEditButtons.forEach(button => {
        button.addEventListener('click', function () {
            const routeId = this.getAttribute('data-id');
            const name = this.getAttribute('data-name');
            const startPoint = this.getAttribute('data-start-point');
            const endPoint = this.getAttribute('data-end-point');
            const distance = this.getAttribute('data-distance');
            const estimatedTime = this.getAttribute('data-estimated-time');
            const status = this.getAttribute('data-status');

            // 打开编辑路线模态框
            openEditRouteModal(routeId, name, startPoint, endPoint, distance, estimatedTime, status);
        });
    });

    // 初始化编辑路线模态框关闭按钮事件
    const closeEditRouteButton = document.getElementById('close-edit-route-modal');
    if (closeEditRouteButton) {
        closeEditRouteButton.addEventListener('click', closeEditRouteModal);
    }

    // 初始化取消编辑路线按钮事件
    const cancelEditRouteButton = document.getElementById('cancel-edit-route');
    if (cancelEditRouteButton) {
        cancelEditRouteButton.addEventListener('click', closeEditRouteModal);
    }

    // 初始化编辑路线表单提交事件
    const editRouteForm = document.getElementById('edit-route-form');
    if (editRouteForm) {
        editRouteForm.addEventListener('submit', function (event) {
            event.preventDefault();
            submitEditRouteForm();
        });
    }
}

// 打开添加路线模态框
function openAddRouteModal() {
    console.log('尝试打开添加路线模态框');
    const addRouteModal = document.getElementById('add-routes-modal');
    if (addRouteModal) {
        console.log('找到添加路线模态框');
        // 移除hidden类以显示模态框
        addRouteModal.classList.remove('hidden');
        console.log('模态框类列表:', addRouteModal.classList);
        // 重置表单
        const addRouteForm = document.getElementById('add-route-form');
        if (addRouteForm) {
            addRouteForm.reset();
        }
    } else {
        console.log('未找到添加路线模态框');
    }
}

// 关闭添加路线模态框
function closeAddRouteModal() {
    const addRouteModal = document.getElementById('add-routes-modal');
    const addRouteForm = document.getElementById('add-route-form');
    if (addRouteModal) {
        // 添加hidden类以隐藏模态框
        addRouteModal.classList.add('hidden');
    }
    // 重置表单
    if (addRouteForm) {
        addRouteForm.reset();
    }
}

// 打开编辑路线模态框
function openEditRouteModal(routeId, name, startPoint, endPoint, distance, estimatedTime, status) {
    console.log('尝试打开编辑路线模态框');
    const editRouteModal = document.getElementById('edit-routes-modal');
    if (editRouteModal) {
        console.log('找到编辑路线模态框');
        // 填充路线数据
        document.getElementById('edit-route-id').value = routeId;
        document.getElementById('edit-route-name').value = name;
        document.getElementById('edit-route-start-point').value = startPoint;
        document.getElementById('edit-route-end-point').value = endPoint;
        document.getElementById('edit-route-distance').value = distance;
        document.getElementById('edit-route-estimated-time').value = estimatedTime;
        document.getElementById('edit-route-status').value = status;

        // 移除hidden类以显示模态框
        editRouteModal.classList.remove('hidden');
        updateModalOverlay();
    } else {
        console.log('未找到编辑路线模态框');
    }
}

// 关闭编辑路线模态框
function closeEditRouteModal() {
    const editRouteModal = document.getElementById('edit-routes-modal');
    const editRouteForm = document.getElementById('edit-route-form');
    if (editRouteModal) {
        // 添加hidden类以隐藏模态框
        editRouteModal.classList.add('hidden');
        updateModalOverlay();
    }
    // 重置表单
    if (editRouteForm) {
        editRouteForm.reset();
    }
}

// 关闭查看路线模态框
function closeViewRouteModal() {
    const viewRouteModal = document.getElementById('view-route-modal');
    if (viewRouteModal) {
        // 添加hidden类以隐藏模态框
        viewRouteModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 提交编辑路线表单
function submitEditRouteForm() {
    const form = document.getElementById('edit-route-form');
    if (!form) return;

    // 获取表单数据
    const routeId = document.getElementById('edit-route-id').value;
    const name = document.getElementById('edit-route-name').value;
    const startPoint = document.getElementById('edit-route-start-point').value;
    const endPoint = document.getElementById('edit-route-end-point').value;
    const distance = document.getElementById('edit-route-distance').value;
    const estimatedTime = document.getElementById('edit-route-estimated-time').value;
    const status = document.getElementById('edit-route-status').value;

    // 模拟表单提交
    console.log('提交编辑路线表单:', {
        routeId,
        name,
        startPoint,
        endPoint,
        distance,
        estimatedTime,
        status
    });

    // 关闭模态框
    closeEditRouteModal();

    // 显示成功通知
    showTopNotification('路线信息已成功更新', 'success');
}

// 打开查看路线模态框
function openViewRouteModal(routeId, name, startPoint, endPoint, distance, estimatedTime, status) {
    console.log('打开查看路线模态框，路线ID:', routeId);
    const viewRouteModal = document.getElementById('view-routes-modal');
    if (!viewRouteModal) {
        console.error('未找到查看路线模态框');
        return;
    }

    // 填充模态框内容
    document.getElementById('view-route-name').textContent = name || '未知';
    document.getElementById('view-route-start').textContent = startPoint || '未知';
    document.getElementById('view-route-end').textContent = endPoint || '未知';
    document.getElementById('view-route-courier').textContent = '未知'; // 负责人
    document.getElementById('view-route-estimated-time').textContent = estimatedTime || '未知';
    document.getElementById('view-route-description').textContent = '暂无描述';
    document.getElementById('view-route-created-time').textContent = '未知';
    document.getElementById('view-route-updated-time').textContent = '未知';

    // 显示模态框
    viewRouteModal.classList.remove('hidden');
    updateModalOverlay();
}

// 关闭查看路线模态框
function closeViewRouteModal() {
    const viewRouteModal = document.getElementById('view-routes-modal');
    if (viewRouteModal) {
        viewRouteModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 提交添加路线表单
function submitAddRouteForm() {
    // 获取表单数据
    const routeName = document.getElementById('new-route-name').value.trim();
    const start = document.getElementById('new-route-start').value.trim();
    const end = document.getElementById('new-route-end').value.trim();
    const courier = document.getElementById('new-route-courier').value;
    const estimatedTime = document.getElementById('new-route-estimated-time').value;
    const description = document.getElementById('new-route-description').value.trim();

    // 表单验证
    if (!routeName || !start || !end || !estimatedTime) {
        showTopNotification('请填写所有必填字段', 'error');
        return;
    }

    // 模拟API请求添加路线
    console.log('提交添加路线表单:', {
        routeName,
        start,
        end,
        courier,
        estimatedTime,
        description
    });

    // 这里可以添加实际的API调用逻辑
    // 为了演示，我们使用setTimeout模拟异步请求
    setTimeout(function () {
        // 关闭模态框
        closeAddRouteModal();
        // 显示成功通知
        showTopNotification('路线添加成功！', 'success');
        // 这里可以添加刷新路线列表的逻辑
    }, 1000);
}

// DOM加载完成后初始化（确保早于window.load）
document.addEventListener('DOMContentLoaded', function () {
    // 初始化添加角色按钮事件
    // 使用更具体的选择器，避免与添加用户按钮冲突
    const addRoleButton = document.querySelector('a[onclick*="openAddRoleModal"]');
    if (addRoleButton) {
        console.log('找到添加角色按钮，准备绑定事件');
        // 使用箭头函数确保this指向正确
        addRoleButton.addEventListener('click', function (event) {
            event.preventDefault();
            console.log('添加角色按钮被点击');
            openAddRoleModal();
        });
        console.log('添加角色按钮事件已绑定');
    } else {
        console.log('未找到添加角色按钮');
    }

    // 初始化取消添加角色按钮事件
    const cancelAddRoleButton = document.getElementById('cancel-add-role');
    if (cancelAddRoleButton) {
        cancelAddRoleButton.addEventListener('click', closeAddRoleModal);
    }

    // 初始化添加角色表单提交事件
    const addRoleForm = document.getElementById('add-role-form');
    if (addRoleForm) {
        addRoleForm.addEventListener('submit', submitAddRoleForm);
    }
});

// 打开添加物流员模态框
function openAddCourierModal() {
    const addCourierModal = document.getElementById('add-couriers-modal');
    if (addCourierModal) {
        // 移除hidden类以显示模态框
        addCourierModal.classList.remove('hidden');
    }
}

// 关闭添加物流员模态框
function closeAddCourierModal() {
    const addCourierModal = document.getElementById('add-couriers-modal');
    const addCourierForm = document.getElementById('add-courier-form');
    if (addCourierModal) {
        // 添加hidden类以隐藏模态框
        addCourierModal.classList.add('hidden');
    }
    // 重置表单
    if (addCourierForm) {
        addCourierForm.reset();
    }
}

// 提交添加物流员表单
function submitAddCourierForm() {
    // 获取表单数据
    const name = document.getElementById('new-courier-name').value.trim();
    const phone = document.getElementById('new-courier-phone').value.trim();
    const region = document.getElementById('new-courier-region').value.trim();
    const status = document.getElementById('new-courier-status').value;
    const idCard = document.getElementById('new-courier-id-card').value.trim();

    // 表单验证
    if (!name || !phone || !region || !idCard) {
        showTopNotification('请填写所有必填字段', 'error');
        return;
    }

    // 模拟API请求添加物流员
    console.log('提交添加物流员表单:', {
        name,
        phone,
        region,
        status,
        idCard
    });

    // 这里可以添加实际的API调用逻辑
    // 为了演示，我们使用setTimeout模拟异步请求
    setTimeout(function () {
        // 关闭模态框
        closeAddCourierModal();
        // 显示成功通知
        showTopNotification('物流员添加成功！', 'success');
        // 这里可以添加刷新物流员列表的逻辑
    }, 1000);
}

// 打开添加用户模态框
function openAddUserModal() {
    const addUserModal = document.getElementById('add-user-modal');
    if (addUserModal) {
        // 移除hidden类以显示模态框
        addUserModal.classList.remove('hidden');
    }
}

// 关闭添加用户模态框
function closeAddUserModal() {
    const addUserModal = document.getElementById('add-user-modal');
    const addUserForm = document.getElementById('add-user-form');
    if (addUserModal) {
        // 添加hidden类以隐藏模态框
        addUserModal.classList.add('hidden');
    }
    // 重置表单
    if (addUserForm) {
        addUserForm.reset();
    }
}

// 打开添加角色模态框
function openAddRoleModal() {
    // 添加明显的测试提示
    alert('添加角色按钮被点击！');

    console.log('尝试打开添加角色模态框');
    const addRoleModal = document.getElementById('add-roles-modal');
    if (addRoleModal) {
        console.log('找到添加角色模态框');
        // 移除hidden类以显示模态框
        addRoleModal.classList.remove('hidden');
        console.log('模态框类列表:', addRoleModal.classList);
        // 重置表单
        const addRoleForm = document.getElementById('add-role-form');
        if (addRoleForm) {
            addRoleForm.reset();
        }
    } else {
        console.log('未找到添加角色模态框');
    }
}

// 关闭添加角色模态框
function closeAddRoleModal() {
    const addRoleModal = document.getElementById('add-roles-modal');
    if (addRoleModal) {
        // 添加hidden类以隐藏模态框
        addRoleModal.classList.add('hidden');
    }
}

// 打开编辑角色模态框
function openEditRoleModal(roleId, roleName = '', roleDescription = '', permissions = []) {
    console.log('尝试打开编辑角色模态框，角色ID:', roleId);
    const editRoleModal = document.getElementById('edit-roles-modal');
    if (editRoleModal) {
        console.log('找到编辑角色模态框');
        
        // 填充表单数据
        document.getElementById('edit-role-id').value = roleId;
        document.getElementById('edit-role-name').value = roleName;
        document.getElementById('edit-role-description').value = roleDescription;
        
        // 处理权限复选框
        document.querySelectorAll('input[name="edit-permissions"]').forEach(checkbox => {
            checkbox.checked = permissions.includes(checkbox.value);
        });

        // 移除hidden类以显示模态框
        editRoleModal.classList.remove('hidden');
        updateModalOverlay();
    } else {
        console.error('未找到编辑角色模态框元素');
    }
}

// 关闭编辑角色模态框
function closeEditRoleModal() {
    const editRoleModal = document.getElementById('edit-roles-modal');
    if (editRoleModal) {
        // 添加hidden类以隐藏模态框
        editRoleModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 打开删除角色模态框
function openDeleteRoleModal(roleId, roleName = '', userCount = 0) {
    console.log('尝试打开删除角色模态框，角色ID:', roleId);
    const deleteRoleModal = document.getElementById('delete-roles-modal');
    if (deleteRoleModal) {
        console.log('找到删除角色模态框');
        // 显示角色名称和关联用户数量
        document.getElementById('delete-role-name').textContent = roleName;
        document.getElementById('delete-role-user-count').textContent = userCount;
        // 存储角色ID以便后续使用
        document.getElementById('delete-role-id').value = roleId;
        // 移除hidden类以显示模态框
        deleteRoleModal.classList.remove('hidden');
        updateModalOverlay();
    } else {
        console.error('未找到删除角色模态框元素');
    }
}

// 关闭删除角色模态框
function closeDeleteRoleModal() {
    const deleteRoleModal = document.getElementById('delete-roles-modal');
    if (deleteRoleModal) {
        // 添加hidden类以隐藏模态框
        deleteRoleModal.classList.add('hidden');
        updateModalOverlay();
    }
}

// 提交添加角色表单
function submitAddRoleForm(event) {
    event.preventDefault();
    // 获取表单数据
    const roleName = document.getElementById('new-role-name').value.trim();
    const roleDescription = document.getElementById('new-role-description').value.trim();
    const permissions = Array.from(document.querySelectorAll('input[name="permissions"]:checked'))
        .map(checkbox => checkbox.value);

    // 表单验证
    if (!roleName || !roleDescription) {
        showTopNotification('请填写角色名称和描述', 'error');
        return;
    }

    if (permissions.length === 0) {
        showTopNotification('请至少选择一项权限', 'error');
        return;
    }

    // 构建请求数据
    const data = {
        name: roleName,
        description: roleDescription,
        permissions: permissions
    };

    // 发送API请求添加角色
    apiService.fetch('/api/roles', {
        method: 'POST',
        body: JSON.stringify(data)
    })
    .then(response => {
        if (response.success) {
            console.log('角色添加成功:', response.data);
            // 关闭模态框
            closeAddRoleModal();
            // 显示成功通知
            showTopNotification('角色添加成功！', 'success');
            // 刷新角色列表
            loadRolesData();
        } else {
            throw new Error(response.message || '添加角色失败');
        }
    })
    .catch(error => {
        console.error('添加角色失败:', error);
        showTopNotification('添加角色失败: ' + (error.message || '未知错误'), 'error');
    });
}

// 提交编辑角色表单
function submitEditRoleForm(event) {
    event.preventDefault();
    // 获取表单数据
    const roleId = document.getElementById('edit-role-id').value;
    const roleName = document.getElementById('edit-role-name').value.trim();
    const roleDescription = document.getElementById('edit-role-description').value.trim();
    const permissions = Array.from(document.querySelectorAll('input[name="edit-permissions"]:checked'))
        .map(checkbox => checkbox.value);

    // 表单验证
    if (!roleId || !roleName || !roleDescription) {
        showTopNotification('请填写角色名称和描述', 'error');
        return;
    }

    if (permissions.length === 0) {
        showTopNotification('请至少选择一项权限', 'error');
        return;
    }

    // 构建请求数据
    const data = {
        name: roleName,
        description: roleDescription,
        permissions: permissions
    };

    // 发送API请求更新角色
    apiService.fetch(`/api/roles/${roleId}`, {
        method: 'PUT',
        body: JSON.stringify(data)
    })
    .then(response => {
        if (response.success) {
            console.log('角色更新成功:', response.data);
            // 关闭模态框
            closeEditRoleModal();
            // 显示成功通知
            showTopNotification('角色更新成功！', 'success');
            // 刷新角色列表
            loadRolesData();
        } else {
            throw new Error(response.message || '更新角色失败');
        }
    })
    .catch(error => {
        console.error('更新角色失败:', error);
        showTopNotification('更新角色失败: ' + (error.message || '未知错误'), 'error');
    });
}

// 提交删除角色表单
function submitDeleteRoleForm(event) {
    event.preventDefault();
    // 获取角色ID
    const roleId = document.getElementById('delete-role-id').value;

    if (!roleId) {
        showTopNotification('未选择要删除的角色', 'error');
        return;
    }

    // 发送API请求删除角色
    apiService.fetch(`/api/roles/${roleId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showTopNotification('角色删除成功');
            closeDeleteRoleModal();
            loadRolesData(); // 重新加载角色数据
        } else {
            showTopNotification('角色删除失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('删除角色失败:', error);
        showTopNotification('删除角色失败: ' + (error.message || '未知错误'), 'error');
    });
}

// 提交添加用户表单
function submitAddUserForm() {
    // 获取表单数据
    const username = document.getElementById('new-username').value.trim();
    const email = document.getElementById('new-email').value.trim();
    const phone = document.getElementById('new-phone').value.trim();
    const role = document.getElementById('new-role').value;
    const password = document.getElementById('new-password').value;
    const confirmPassword = document.getElementById('confirm-password').value;

    // 表单验证
    if (!username || !email || !phone || !password || !confirmPassword) {
        showTopNotification('请填写所有必填字段', 'error');
        return;
    }

    if (password !== confirmPassword) {
        showTopNotification('两次输入的密码不一致', 'error');
        return;
    }

    if (password.length < 6) {
        showTopNotification('密码长度不能少于6位', 'error');
        return;
    }

    // 模拟API请求添加用户
    console.log('提交添加用户表单:', {
        username,
        email,
        phone,
        role,
        password
    });

    // 这里可以添加实际的API调用逻辑
    // 为了演示，我们使用setTimeout模拟异步请求
    setTimeout(function () {
        // 关闭模态框
        closeAddUserModal();
        // 显示成功通知
        showTopNotification('用户添加成功！', 'success');
        // 这里可以添加刷新用户列表的逻辑
    }, 1000);
}